<template>

  <div class="container">
    <div ref="chart" class="echart"/>
    <p class="overlay">{{stockName}} {{ stockCode }}</p>
  </div>

</template>

<script>
import * as echarts from "echarts";
import axios from "axios";

export default {
  data() {
    return {
      code:'886044',
      dayTime: this.formatDate(new Date()),
      dayCount:100,
      upColor: "#FD1050",
      downColor: "#0CF49B",

      close:10,
      allData: [],
      timeRecord: [],
      price: [],
      changeAment: [], // 百分比
      volume: [],
      increase:[],
      turnover: [],

      startPercent:0,
      endPercent:100,
      calculateAvgPrice: [],
      open: 10,
      yAxisMin: 0,
      yAxisMax: 10,
      calInterval: 5,
    };
  },
  computed: {
    stockCode() {
      const value = this.$store.getters.getStockCode
      console.log('stockCode', value);
      this.code = value;
      this.fetchData();
      return value;
    },
    stockName() {
      const value = this.$store.getters.getStockName;
      return value;
    }
  },
  mounted() {
    this.fetchData();
  },
  props: {
        num: 0,
        time:'2024-08-02',
  },
  watch: {
      num(val,oldValue) {
        this.dayCount = val
        // this.fetchData();
      },
      time(val,oldValue) {
        this.dayTime = val
        this.fetchData();
      }
  },
  methods: {
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要 +1，并确保两位数
      const day = String(date.getDate()).padStart(2, '0'); // 确保两位数
      return `${year}-${month}-${day}`;
    },
    initChart() {
      const myChart = echarts.init(this.$refs.chart);
      const option = {
        xAxis: [
          {
            type: "category",
            data: this.timeRecord,
            axisLabel: {
              // x轴标签相关设置
              formatter: function (value, index) {
                return value.substring(11, 16);
              },
            },
          },
          {
            data: this.timeRecord,
            gridIndex: 1,
            axisLabel: {
              // x轴标签相关设置
              formatter: function (value, index) {
                return value.substring(11, 16);
              },
            },
          },
        ],

        yAxis: [
          {
            type: "value",
            min: this.yAxisMin,
            max: this.yAxisMax,
            interval: this.calInterval,
            axisLabel: {
              // x轴标签相关设置
              formatter: function (value, index) {
                return value.toFixed(2);
              },
            },
            axisPointer: {
              show: true,
              label: {
                show: true, // 显示标签
                formatter: (params) => {
                  return params.value.toFixed(2);
                },
              },
            },
            splitLine: {
              // 将Y轴的分割线设置为虚线
              show: true,
              lineStyle: {
                type:'dotted',
                color: ['#cccccc50', '#cccccc80', '#cccccc80', '#333333','#cccccc80', '#cccccc80', '#cccccc80'], // 分割线颜色
              },
            },
          },
          {
            type: "value",
            min: this.yAxisMin,
            max: this.yAxisMax,
            position: "right",
            interval: this.calInterval,
            axisLabel: {
              // x轴标签相关设置
              color: (value) => {
                console.log("val:", value - this.open);
                if (-0.001 <= value - this.open && value - this.open <= 0.001) {
                  // value1 8.3000001
                  return "#333";
                } else {
                  return value > this.open ? this.upColor : this.downColor;
                }
              },
              formatter: (value, index) => {
                return (
                  (((value - this.open) / this.open) * 100).toFixed(2) + "%"
                ); ////
              },
            },
            axisPointer: {
              show: true,
              label: {
                show: true, // 显示标签
                formatter: (params) => {
                  return (
                    (((params.value - this.open) / this.open) * 100).toFixed(
                      2
                    ) + "%"
                  );
                },
              },
            },
            splitLine: {
              // 将Y轴的分割线设置为虚线
              show: false,
            },
          },
          { // 成交量
            gridIndex: 1,
          }
        ],

        grid: [
          {
            top: "1%",
            bottom: "40%",
          },
          {
            top: "73%",
          },
        ],

        series: [
          {
            name:"price",
            type: "line",
            data: this.price,
            smooth: true,
            symbol: "none", //隐藏选中时有小圆点
          },
          {
            type: "line",
            data: this.calculateAvgPrice,
            smooth: true,
            symbol: "none", //隐藏选中时有小圆点
          },
          {
            name:"volume",
            type: "bar",
            data: this.volume,
            xAxisIndex: 1,
            yAxisIndex: 2,
            itemStyle: {   
              color: (params) => {
                return this.downColor;
                // return this.increase[params.dataIndex] > 0 ? this.upColor : this.downColor; 
              }
            }
          },
        ],

        dataZoom: [
          {
            type: "slider", // 设置为slider类型
            show: true, // 是否显示滑动条
            xAxisIndex: [0, 1], // 指定作用于哪个坐标轴，K线图通常只有一个x轴
            start: this.startPercent, // 初始时数据窗口的起始百分比
            end: this.endPercent, // 初始时数据窗口的结束百分比，这里只显示10%的数据
            // 其他可选配置...
          },
          {
            type: "inside", // 另一种dataZoom，允许通过鼠标滚轮缩放
            xAxisIndex: [0, 1],
            zoomOnMouseWheel: true, // 是否启用鼠标滚轮缩放
          },
        ],

        tooltip: {  
            trigger: 'axis', // 触发类型，默认数据项触发，可选为：'item' | 'axis'  
            formatter: (params, ticket, callback) => {
              const item = params[0];
              console.log('params:', params);
              var html = "<div></dive>"
              if (item.seriesName === "volume") {
                console.log('params:', params[0]);
                // var volume =this.volume[item.dataIndex];
                // var change = this.increase[item.dataIndex];
                // var color = change > 0 ? 'style="color:#ff4242"' : 'style="color:#26bf66"';
                // var increase = this.increase[item.dataIndex];
                // var normalColor = "color:#333";
                // html = '<div class="commColor" style="width:160px;margin-right: 20px;">';
                // html += '<div>日期  <span  '+normalColor+' >' + this.timeRecord[item.dataIndex] + '</span></div>';             
                // html += '<div>成交量  <span  '+color+' >' + volume + '万手</span></div></div>';
                // html += '<div>涨跌额  <span  '+color+' >' + change.toFixed(2) + '元</span></div></div>';
                var price = this.price[item.dataIndex];  
                var increase = ((price - this.close) * 100 / this.close).toFixed(2);

                var color = increase > 0 ? 'style="color:#ff4242;font-size:22px"' : 'style="color:#26bf66;font-size:22px"';
                var colorTime = increase > 0 ? 'style="font-size:22px"' : 'style="font-size:22px"';

                html += '<div>时间  <span  '+colorTime+' >' + this.timeRecord[item.dataIndex].substring(11,16) + '</span></div>';
                html += '<div>涨跌  <span  '+color+' >' + increase + '%</span></div></div>';
                return html;
              } else {
                //  var volume =this.volume[item.dataIndex];
                //  var change = this.increase[item.dataIndex];
                //  var upDown = change > 0 ? '+' : '';
                //  var color = change > 0 ? 'style="color:#ff4242"' : 'style="color:#26bf66"';
                //  
                
                // html = '<div class="commColor" style="width:160px;margin-right: 25px;">';
                // html += '<div>日期  <span  '+normalColor+' >' + this.timeRecord[item.dataIndex] + '</span></div>';
                // html += '<div>涨跌  <span  '+color+' ><strong>' + upDown + change.toFixed(2) + '元</strong></span></div></div>';
                // html += '<div>成交量  <span  '+color+' >' + volume + '万手</span></div></div>';
                var price = this.price[item.dataIndex];  
                var increase = ((price - this.close) * 100 / this.close).toFixed(2);

                var color = increase > 0 ? 'style="color:#ff4242;font-size:22px"' : 'style="color:#26bf66;font-size:22px"';
                var colorTime = increase > 0 ? 'style="font-size:22px"' : 'style="font-size:22px"';

                html += '<div>时间  <span  '+colorTime+' >' + this.timeRecord[item.dataIndex].substring(11,16) + '</span></div>';
                html += '<div>涨跌  <span  '+color+' >' + increase + '%</span></div></div>';
                return html;
              }
              return html;
            },
            axisPointer: {  
                type: 'cross', // 默认为直线，可选为：'line' | 'shadow'  
            }  
        }, 
      };

      myChart.setOption(option);
    },

    async fetchData() {
      try {
        const response = await axios.get(
          "api/plat/stock/getStockNowData?stockCode=" + this.code +
            "&queryTime=" + this.dayTime + "&allCount=1000"
        );

        const result = response.data;
        console.log("请求结果:", result);
        if (result.status == 200) {
          console.log("请求成功:", result);

          this.close = result.close;
          this.timeRecord = [];
          this.price = [];
          this.changeAment = [];
          this.increase = [];
          this.volume = [];
          this.turnover = [];
          this.allData = result.data;
          this.open = Math.abs(result.close);
          this.allData.forEach((item) => {
            // 对item进行所需的操作
            this.timeRecord.push(item.timeRecord);
            this.price.push(item.price);
            this.changeAment.push(item.changeAment);
            this.volume.push(Number(item.volume / 10000).toFixed(2))
            this.turnover.push(item.turnover);
            this.increase.push(item.increase);
          });

          console.log(this.timeRecord);
          console.log("价格：" + this.price);
          this.calculateHighLow();
        } else {
          console.error("请求失败:");
        }
      } catch (error) {
        console.error("请求error:", error);
      }
    },

    calculateHighLow() {
      // 计算最大值和最小值
      // const open = this.price[0]; // 开盘价
      const maxPrice = Math.max(...this.price); // 找到最高价中的最大值
      const minPrice = Math.min(...this.price); // 找到最低价中的最小
      const open = this.open; // 昨日收盘价
      console.error("昨日收盘价:", open);
      var minVal = minPrice; // Math.min(...data.price);
      var maxVal = maxPrice; // Math.max(...data.price);
      var interval;
      if (open > maxVal) {
        interval = (open - minVal) / 3;
      } else {
        const absMaxDiff = Math.abs(open - maxVal);
        const absMinDiff = Math.abs(open - minVal);
        const diff = absMaxDiff > absMinDiff ? absMaxDiff : absMinDiff;
        interval = diff / 3;//+ Number(((open * 0.01) / 3).toFixed(2)); // 大5%, 3上下的分割线数量
      }
      minVal = (open - interval * 3).toFixed(2);
      maxVal = (open + interval * 3).toFixed(2);
      this.open = open;
      this.yAxisMax = maxVal;
      this.yAxisMin = minVal;
      this.calInterval = interval;
      console.log(open + " " + maxPrice + " " + minPrice);

      // 计算均价线:WMA加权平均
      this.calculateAvgPrice = [];
      for (let i = 0; i < this.allData.length; i++) {
        const totalVolume = this.allData
            .slice(0, i)
            .reduce((acc, curr) => acc + curr.volume, 0);
          const totalAmount = this.allData
            .slice(0, i)
            .reduce((acc, curr) => acc + Math.abs(curr.price) * curr.volume, 0);
          const avgPrice = totalAmount / totalVolume;
          this.calculateAvgPrice.push(avgPrice);
      }

      console.log(this.calculateAvgPrice);

      this.initChart();
    },
  },
};
</script>

<style  scoped>
.echart {
  width: 100%; height: 725px;
}
.container {
    flex: 77; /* 75% */
}
.overlay {
  position: absolute; /* 设置为绝对定位 */
  top: 0%;
  left: 35%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 17px;
  font-weight: bold;
  font-family: 'Hiragino Sans GB'/* Inter, 'Helvetica Neue', Helvetica, 'PingFang SC',
  'Hiragino Sans GB', 'Microsoft YaHei' */
}
</style>